package com.example.order.service.impl;

import com.example.order.entity.OrderEntity;
import com.example.order.entity.OrderStatus;
import com.example.order.repository.OrderRepository;
import com.example.order.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author : zhayh
 * @date : 2021-5-8 15:37
 * @description :
 */

@Service
@Slf4j
public class UserOrderServiceImpl implements UserOrderService {
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderQueueService orderQueueService;

    @Override
    public OrderEntity createOrder(String goodsName, Long goodsCount, Long goodsPrice,
                                   Long totalPrice, String user) {
        log.info("用户数据服务，创建新订单： {}", user);
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderCode(getNewOrderCode());
        orderEntity.setOrderUser(user);
        orderEntity.setGoodsCount(goodsCount);
        orderEntity.setOrderTime(LocalDateTime.now());
        orderEntity.setOrderStatus(OrderStatus.INIT.getName());
        orderEntity.setGoodsName(goodsName);
        orderEntity.setGoodsPrice(goodsPrice);
        orderEntity.setOrderTotalPrice(totalPrice);
        log.info("用户数据服务，订单创建完成： {}", user);
        orderEntity = orderRepository.save(orderEntity);

        // 向队列1发送订单创建完成消息
        orderQueueService.sendCreateMessage(orderEntity.getOrderCode());
        return orderEntity;
    }

    @Override
    public List<OrderEntity> getMyOrders(String user) {
        return orderRepository.findByOrderUserOrderByOrderConfirmTimeDesc(user);
    }

    @Override
    public OrderEntity finishOrder(String orderCode) {
        OrderEntity orderEntity = orderRepository.findByOrderCode(orderCode);
        if (orderEntity != null) {
            orderEntity.setOrderStatus(OrderStatus.COMPLETE.getName());
            orderRepository.save(orderEntity);
            log.info("用户数据服务，订单完成：{}", orderCode);
            return orderEntity;
        }
        return null;
    }

    private String getNewOrderCode() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("DDyyyyMMHHmmssSS"));
    }

    // 用户监听队列4，实现订单完成
    @RabbitListener(queues = "queue.order.complete")
    public void listenShopDeliver(String message){
        log.info("用户数据服务，收到配送完成消息，订单完成： {}", message);
        OrderEntity orderEntity = finishOrder(message);
    }
}
